﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using QXBook.Model;
using System.Text;

namespace Web.App_Code
{
    public class ClientPager
    {
        /// <summary>
        /// 前台的分页
        /// </summary>
        /// <param name="ds">DataSet实例</param>
        /// <param name="datalistname">DataList名称</param>
        /// <param name="pagesize">分页大小</param>
        public static string CreatePager(PagerState ps)
        {
            int next = 0;
            int pre = 0;
            int startcount = 0;
            int endcount = 0;
            StringBuilder pagestr = new StringBuilder();
            if (ps.CurrentPage < 1) { ps.CurrentPage = 1; }


            next = ps.CurrentPage + 1;
            pre = ps.CurrentPage - 1;
            startcount = (ps.CurrentPage + 5) > ps.PageCount ? ps.PageCount - 9 : ps.CurrentPage - 4;//中间页起始序号
            //中间页终止序号
            endcount = ps.CurrentPage < 5 ? 10 : ps.CurrentPage + 5;

            //为了避免输出的时候产生负数，设置如果小于1就从序号1开始
            if (startcount < 1)
            {
                startcount = 1;
            }

            //页码+5的可能性就会产生最终输出序号大于总页码，那么就要将其控制在页码数之内
            if (ps.PageCount < endcount) {
                endcount = ps.PageCount; 
            }
            pagestr.Append(@"<div class=""page"">");
            pagestr.Append(ps.PageCount > 1 ? "<a href=\"" + HttpContext.Current.Request.CurrentExecutionFilePath + "?page=1\">首页</a>&nbsp;<a href=\"" + HttpContext.Current.Request.CurrentExecutionFilePath + "?page=" + pre + "\">上页</a>" : "<a>首页</a>" + "&nbsp;" + "<a>上页</a>");
            //中间页处理，这个增加时间复杂度，减小空间复杂度
            for (int i = startcount; i <= endcount; i++)
            {
                pagestr.Append(ps.PageCount == i ? "&nbsp;" + "<a class=\"cpb\">[" + i + "]</a>" : "&nbsp;<a href=\"" + HttpContext.Current.Request.CurrentExecutionFilePath + "?page=" + i + "\">" + i + "</a>");
            }
            pagestr.Append(ps.PageSize != ps.PageCount ? "&nbsp;<a href=\"" + HttpContext.Current.Request.CurrentExecutionFilePath + "?page=" + next + "\">下页</a>&nbsp;<a href=\"" + HttpContext.Current.Request.CurrentExecutionFilePath + "?page=" + ps.PageCount + "\">尾页</a>" : "&nbsp;" + "<a >下页</a>" + "&nbsp;" + "<a >尾页</a>");
            pagestr.Append("共" + ps.PageCount + "页 每页" + ps.PageSize + "条 " + "共" + ps.RecordCount + "条记录");
            pagestr.Append("</div>");
            return pagestr.ToString();
        }
    }
}